package com.gz.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.gz.common.Idempotent;
import com.gz.config.AlipayConfigOriginal;
import com.gz.entity.OrderRequest;
import com.gz.entity.OrderStatus;
import com.gz.entity.Vo.OrderVo;
import com.gz.exception.Assert;
import com.gz.exception.BusinessCode;
import com.gz.exception.SystemCode;
import com.gz.service.OrderService;
import com.gz.util.JwtUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
//@Api(tags = "购物车接口")
@Slf4j
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;  //要实现会话跟踪，从Token中获取用户id

    @PostMapping("/addNewOrder/{userId}")
    @Idempotent  //使用幂等注解
    public ResponseEntity<?> addNewOrder(@PathVariable Long userId, @RequestBody OrderRequest request) {
        //获取uniqueCode和addressId
        String uniqueCode = request.getUniqueCode();
        Integer addressId = request.getAddressId();
        log.info("uniqueCode: {}, addressId: {}", uniqueCode, addressId);
        Assert.error(addressId==null, BusinessCode.NULL_ADDRESS);
//        // 判断Redis中唯一标识是否已经存在，如果存在则直接返回。键：唯一标识，值：1， 15秒后过期
//        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(uniqueCode, 1, Duration.ofSeconds(15));
//        //如果返回true，表示设置成功，如果返回false，表示已经提交过，返回错误
//        Assert.error(!ifAbsent, BusinessCode.REPEAT_COMMIT);

        String orderNum = orderService.addNewOrder(userId, addressId);
        return ResponseEntity.ok(SystemCode.SUCCESS_ADD_ORDER.getMessage()+",订单编号："+orderNum);
    }

    @GetMapping("/loadOrdersByStatus/{userId}/{status}")
//    @ApiOperation("查询指定状态的订单")
    public ResponseEntity<List<OrderVo>> loadOrdersByStatus(@PathVariable Long userId,@PathVariable Integer status) {
        List<OrderVo> orderVos = orderService.queryOrder(userId, status);
        return ResponseEntity.ok(orderVos);
    }
    @PostMapping("/pay/{orderIdStr}/{uniqueCode}")
    public ResponseEntity<?> pay(@PathVariable String orderIdStr,@PathVariable String uniqueCode) {
        //调用业务层支会
        String form = orderService.pay(Long.valueOf(orderIdStr));
        return ResponseEntity.ok(form);
    }


    @Autowired
    private AlipayConfigOriginal alipayConfigOriginal;

    /**
     - 支付宝异步回调接口
     - http://内网穿透地址/order/notify
     */
    @SneakyThrows
    @PostMapping("/notify")
    public void aliPayNotify(HttpServletRequest request) {
        //获取所有请求参数，重新创建一个Map再封装一次数据
        Map<String, String> params = request.getParameterMap().entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0]));
        // 验证签名
        String sign = params.get("sign");
        String contentV1 = AlipaySignature.getSignCheckContentV1(params);
        boolean rsa256CheckSignature = AlipaySignature.rsa256CheckContent(contentV1,
                sign, alipayConfigOriginal.getAlipayPublicKey(), "UTF-8");

        //表示支付成功
        if (rsa256CheckSignature && "TRADE_SUCCESS".equals(params.get("trade_status"))) {
            // 签名验证成功 并且 支付宝回调的状态是成功状态 TRADE_SUCCESS
            log.info("在{}，买家{}进行订单{}的付款，交易名称{}，付款金额{}", params.get("gmt_payment"), params.get("buyer_id"),
                    params.get("out_trade_no"), params.get("subject"), params.get("total_amount"));
            // 支付成功，修改数据库中该订单的状态，out_trade_no即订单ID
            String outTradeNo = params.get("out_trade_no");
            //更新订单状态为待发货
            orderService.updateOrderStatus(outTradeNo, OrderStatus.NO_SEND.getCode());
            log.info("订单{}支付成功，状态修改为待发货", outTradeNo);
        } else {
            log.error("支付宝支付失败");
        }
    }

    @DeleteMapping("/cancelOrder/{userId}/{orderId}")
    public ResponseEntity<?> cancelOrder(@PathVariable Long userId,@PathVariable String orderId) {
        orderService.cancelOrder(userId,orderId);
        return ResponseEntity.ok(SystemCode.SUCCESS_CANCEL_ORDER.getMessage());
    }

    @DeleteMapping("/deleteOrder/{userId}/{orderId}")
    public ResponseEntity<?> deleteOrder(@PathVariable Long userId,@PathVariable String orderId) {
        orderService.deleteOrder(userId,orderId);
        return ResponseEntity.ok(SystemCode.SUCCESS_DELETE_ORDER.getMessage());
    }
}